<?php
require_once('db.inc.php');
require_once('annonce.class.php');
require_once('type_transaction.class.php');
require_once('type_bien.class.php');
require_once('localisation.class.php');
require_once('../lib/phpmailer/class.phpmailer.php');

class alerte_mail {
	var $id;
	var $mail;
	var $civilite;
	var $nom;
	var $prenom;
	var $salt;
	var $is_active;
	var $type_transaction;
	var $type_bien;
	var $localisation;
	var $prix_mini;
	var $prix_maxi;
	var $surface_mini;
	var $surface_maxi;
	var $piece_mini;
	var $piece_maxi;
	var $created_at;
	var $compteur;

	function alerte_mail($id=0)
	{
		$this->id = $id;
		$this->type_transaction = new type_transaction(DEFAULT_ID);
		$this->type_bien = new type_bien(DEFAULT_ID);
		$this->localisation = new localisation(DEFAULT_ID);
		if ($this->id != 0) {
			$rs = sql_query("SELECT * FROM alerte_mail WHERE id=" . $this->id);
			$this->mail              = $rs->fields['mail'];
			$this->civilite          = $rs->fields['civilite'];
			$this->nom               = stripslashes($rs->fields['nom']);
			$this->prenom            = stripslashes($rs->fields['prenom']);
			$this->salt              = $rs->fields['salt'];
			$this->is_active         = $rs->fields['is_active'];
			$this->type_transaction  = new type_transaction( $rs->fields['type_transaction_id'] );
			$this->type_bien         = new type_bien($rs->fields['type_bien_id']);
			$this->localisation      = new localisation($rs->fields['localisation_id']);
			$this->prix_mini         = $rs->fields['prix_mini'];
			$this->prix_maxi         = $rs->fields['prix_maxi'];
			$this->surface_mini      = $rs->fields['surface_mini'];
			$this->surface_maxi      = $rs->fields['surface_maxi'];
			$this->piece_mini        = $rs->fields['piece_mini'];
			$this->piece_maxi        = $rs->fields['piece_maxi'];
			$this->created_at        = $rs->fields['created_at'];
			$this->compteur          = $rs->fields['compteur'];
		}
	}

	function save()
	{
		global $conn;
		$sql = "INSERT INTO alerte_mail (
		              mail,
		              civilite,
		              nom,
		              prenom,
		              salt,
		              type_transaction_id,
		              type_bien_id,
		              localisation_id,
		              prix_mini,
		              prix_maxi,
		              surface_mini,
		              surface_maxi,
		              piece_mini,
		              piece_maxi,
		              is_active,
		              compteur,
		              created_at
		            ) VALUES (
		              '" . $this->mail . "',
		              '" . $this->civilite . "',
		              '" . addslashes($this->nom) . "',
		              '" . addslashes($this->prenom) . "',
		              '" . $this->getSalt() . "',
		              '" . $this->type_transaction->id . "',
		              '" . $this->type_bien->id . "',
		              '" . $this->localisation->id . "',
		              '" . $this->prix_mini . "',
		              '" . $this->prix_maxi . "',
		              '" . $this->surface_mini . "',
		              '" . $this->surface_maxi . "',
		              '" . $this->piece_mini . "',
		              '" . $this->piece_maxi . "',
		              '0',
		              '0',
		              NOW()
		            )";
        if ($conn->Execute($sql) === false) {
            if ($conn->ErrorNo() == 1062)
                return ERROR_1062;
            else {
                log_error("Erreur MySQL inconnue dans la SAUVEGARDE de l'alerte mail > sql: " . trim($sql));
                return ERROR_MYSQL;
            }
        }
        $this->id = $conn->Insert_ID();
        return true;
	}

	function incrementCounter($nb=1) {
		$sql = "UPDATE alerte_mail
				SET compteur= compteur + " . $nb . "
				WHERE id=" . $this->id . " LIMIT 1";
		$recordSet = sql_query($sql);
		if (!$recordSet) {
			log_error("Erreur MySQL dans l'INCREMENTATION d'une alerte mail > sql: " . trim($sql) . " \nError: " . $conn->ErrorMsg());
			return false;
		}
	}

	function getAll($order='created_at')
	{
		$data = array();
		$recordSet = sql_query("SELECT * FROM alerte_mail ORDER BY " . $order . " DESC");
		while (!$recordSet->EOF) {
			$id = $recordSet->fields['id'];
			$data[$id]['mail'] = $recordSet->fields['mail'];
			$data[$id]['civilite'] = $recordSet->fields['civilite'];
			$data[$id]['nom'] = $recordSet->fields['nom'];
			$data[$id]['prenom'] = $recordSet->fields['prenom'];
			$data[$id]['is_active'] = $recordSet->fields['is_active'];
			$data[$id]['created_at'] = $recordSet->fields['created_at'];
			$data[$id]['compteur'] = $recordSet->fields['compteur'];
			$recordSet->MoveNext();
		}
		return $data;
	}

	function reload()
	{
		$this->alerte_mail($this->id);
	}
	
	function delete()
	{
		sql_query("DELETE FROM alerte_mail WHERE id=" . $this->id);
	}
	
	function purge()
	{
		global $conn;
		$sql = "DELETE FROM alerte_mail
				WHERE TO_DAYS(created_at) < (TO_DAYS(NOW()) - " . ALERTE_NB_DAYS . ")  
				AND is_active=0";
		sql_query($sql);
		return $conn->Affected_Rows();
	}

	function getSalt()
	{
		return md5($this->mail . date(DATE_ATOM));
	}

	function getIdFromSaltAndMail($mail, $salt)
	{
		global $conn;
		$sql = "SELECT id FROM alerte_mail WHERE mail='" . $mail . "' AND salt = '" . $salt . "'";
		$recordSet = sql_query($sql);
		if (!$recordSet) {
		    log_error("Erreur MySQL dans la RECUPERATION d'une alerte mail > sql: " . trim($sql) . " \nError: " . $conn->ErrorMsg());
		    return false;
		}
		$this->id = $recordSet->fields['id'];
		if ($this->id == 0) {
		    return false;
		}
		$this->reload();
		return true;
	
	}

	function activate($mail, $salt)
	{
		if ( !$this->getIdFromSaltAndMail($mail, $salt) ) {
			return false;
		} else {
		    if ($this->is_active == '1') {
		        return 'already_activate';
		    } else {
		        $sql = "UPDATE alerte_mail
		                SET is_active='1',
		                salt = '" . $this->getSalt() . "'
		                WHERE id=" . $this->id . " LIMIT 1";
		        $recordSet = sql_query($sql);
		        if (!$recordSet) {
		            log_error("Erreur MySQL dans l'ACTIVATION d'une alerte mail > sql: " . trim($sql) . " \nError: " . $conn->ErrorMsg());
		            return false;
		        }
		    }
		}
		$this->reload();
		return true;
	}

	function sendMail($action, $data=false)
	{
		$link = URL;
		$subject = "MACI Immobilier - ";
		if ($action=='inscription')
		{
			$link.= 'alerte/alerte.php?salt=' . $this->salt . '&mail=' . $this->mail;
			$subject.= "Activation d'une alerte mail";
			$header = "<p>Votre lien d'activation:<p>";
			$text_header = "Votre lien d'activation:";
		}
		elseif ($action=='annonce')
		{
			$subject.= "Alerte enregistrée!";
			$header = "<p>Les annonces actuelles correspondantes à votre alerte:<p>";
			$text_header = "Les annonces actuelles correspondantes à votre alerte:";
		}
		elseif ($action=='insert')
		{
			$subject.= "Annonce correspondant à votre alerte";
			$header = "<p>Une nouvelle annonce correspond à votre alerte:<p>";
			$text_header = "Une nouvelle annonce correspond à votre alerte:";
		}
		elseif ($action=='update')
		{
			$subject.= "Mise à jour d'une annonce correspondant à votre alerte";
			$header = "<p>Une annonce correspondant à votre alerte a été mise à jour:<p>";
			$text_header = "Une annonce correspondant à votre alerte a été mise à jour";
		}

		// HTML body
		$name = $this->civilite . ' ' . $this->nom . ' ' . $this->prenom;
		$body  = "Bonjour " . $name . ",";
		$body .= $header;
		if($data!==false) { $body.= $data; }
		$body .= '<p><a href="' . $link . '">' . $link . '</a></p>';
		$body .= "<p>" . MAIL_SIGNOFF . "</p>";
		
		// Plain text body (for mail clients that cannot read HTML)
		$text_body  = "Bonjour " . $name . ",\n";
		$text_body .= $text_header;
		if($data!==false) { $text_body.= $data; }
		$text_body .= "\n" . $link;
		$text_body .= MAIL_SIGNOFF;
		
		// Lien de desinscription
		if ($action!='inscription') { 
			$des_link = URL . 'alerte/delete.php?salt=' . $this->salt . '&mail=' . $this->mail;
			$body .= '<p>Pour vous désinscrire, veuillez cliquer sur l\'adresse suivante :<br/><a href="' . $des_link . '">' . $des_link . '</a></p>';
			$text_body .= "Pour vous désinscrire, veuillez cliquer sur l'adresse suivante:\n" . $des_link;
		}

		$mail = new phpmailer();
		$mail->CharSet = 'utf-8';
		$mail->SetLanguage = 'fr';
		$mail->From     = MAIL_ALERTE;
		$mail->FromName = MAIL_ALERTE_NAME;
		$mail->Host     = MAIL_HOST;
		$mail->Mailer   = "smtp";
		$mail->Subject = $subject;
		$mail->Body    = $body;
		$mail->AltBody = $text_body;
		$mail->AddAddress($this->mail, $name);
		$send = $mail->Send();
		
		// Clear all addresses and attachments for next loop
		$mail->ClearAddresses();
		$mail->ClearAttachments();
		
		if($send) {
			return true;
		}
		return false;
	}

	function checkResult($type_transaction_id=DEFAULT_ID, $type_bien_id=DEFAULT_ID, $localisation_id=DEFAULT_ID, $prix=0, $surface=0, $piece=0) {
        $sql = "SELECT id FROM alerte_mail WHERE is_active=1 ";
        $sql.= " AND ( type_transaction_id=" . DEFAULT_ID;
        if ($type_transaction_id!=DEFAULT_ID)
            $sql.= " OR type_transaction_id=" . $type_transaction_id;
        $sql.= " ) AND ( type_bien_id=" . DEFAULT_ID;
        if ($type_bien_id!=DEFAULT_ID)
            $sql.= " OR type_bien_id=" . $type_bien_id;
        $sql.= " ) AND ( localisation_id=" . DEFAULT_ID;
        if ($localisation_id!=DEFAULT_ID)
            $sql.= " OR localisation_id=" . $localisation_id;
        $sql.= " ) AND ( ";
        if ($prix!=0)
        	$sql.= "prix_mini <= " . $prix . " AND prix_maxi >= " . $prix;
		else
        	$sql.= "prix_mini <= 0 AND prix_maxi >= 999999999999";
        $sql.= " ) AND ( ";
        if ($surface!=0)
        	$sql.= "surface_mini <= " . $surface . " AND surface_maxi >= " . $surface;
		else
        	$sql.= "surface_mini <= 0 AND surface_maxi >= 999999999999";
        $sql.= " ) AND ( ";
        if ($piece!=0)
        	$sql.= "piece_mini <= " . $piece . " AND piece_maxi >= " . $piece;
		else
        	$sql.= "piece_mini <= 0 AND piece_maxi >= 99999";
        $sql.= " )  ORDER BY created_at ASC";
		//log_error ( "DEBUG >> requete d'envoi d'alerte automatique:<br/>" . $sql);

		$data = array();
		$recordSet = sql_query($sql);
		while (!$recordSet->EOF) {
			$data[] = $recordSet->fields['id'];
			$recordSet->MoveNext();
		}
		return $data;
	}

	function sendAlerte($annonce, $flag)
	{
		$ids = $this->checkResult($annonce->type_transaction->id, $annonce->type_bien->id, $annonce->localisation->id, $annonce->prix, $annonce->surface, $annonce->piece);

		$success = 0;
		$error = 0;
		if (!empty($ids)) {
			foreach($ids as $alerte_id) {
				$this->id = $alerte_id;
				$this->reload();
				$text = $annonce->displayMiniFiche();
				if ( $this->sendMail($flag, $text) ) {
					$success++;
					$this->incrementCounter();
				} else {
					$error++;
				}
			}
		}
		$ret = array('error'=>$error, 'success'=>$success);
		return ( $ret );
	}

	function sendAllResult() {
		$annonce_ids = annonce::search( $this->type_transaction->id, $this->type_bien->id, $this->localisation->id, $this->prix_mini, $this->prix_maxi, $this->surface_mini, $this->surface_maxi, $this->piece_mini, $this->piece_maxi );
		
		$html = '';
		if (empty($annonce_ids)) {
			$html.= "Aucune annonce ne correspond à votre alerte actuellement.";
		} else {
			$i = 0;
			foreach($annonce_ids as $ann_id) {
				$ann = new annonce($ann_id);
				$html.= $ann->displayMiniFiche();
				$i++;
			}
			$this->incrementCounter($i);
		}
		//echo $html;
		return $this->sendMail('annonce', $html);
	}

}
